#include "hpfconfig.h"
#include "dmdef.h"

namespace HpfConfig
{

BiquadCoeffs calculateCoeffs(double cutoffFreq, PfType type, Slope slope)
{
    BiquadCoeffs coeffs;
    // 1. 查找当前类型+斜率对应的Q值参数
    const FilterParam* param = nullptr;
    for (const auto& p : FILTER) {
        if (p.type == type && p.type == type) {
            const auto &filter = p.param;
            for (const auto &f : filter) {
                if (f.slope == slope) {
                    param = &f;
                    break;
                }
            }
        }
    }
    if (!param) return coeffs; // 错误处理


    // const double w_h = w0*0.5;
    // const double alph_h = tan(w_h);

    double w0 = cutoffFreq * FilterConfig::FS_PI;
    for (size_t i = 0; i < COEFFS_SIZE; ++i) {
        w0 = w0 * param->f[i];
        const double w0_cValue = cos(w0);
        const double w0_sValue = sin(w0);

        const double q = param->q[i];
        if (std::abs(q) < EPSILON_12E) {
            coeffs.a0[i] = 1.0;
            coeffs.a1[i] = 0.0;
            coeffs.a2[i] = 0.0;
            coeffs.b0[i] = 1.0;
            coeffs.b1[i] = 0.0;
            coeffs.b2[i] = 0.0;
        }
        else {
            const auto alphah = w0_sValue * q;
            coeffs.a0[i] = 1.0 + alphah;
            coeffs.a1[i] = -2.0 * w0_cValue;
            coeffs.a2[i] = 1.0 - alphah;
            coeffs.b0[i] = (1.0 + w0_cValue) * 0.5;
            coeffs.b1[i] = -2.0 * coeffs.b0[i];
            coeffs.b2[i] = coeffs.b0[i];
        }
        // if ((slope == Slope::Oct_18dB || slope == Slope::Oct_30dB || slope == Slope::Oct_42dB) && i == 0) {
        //     coeffs.a0[i] = q * alph_h + 1.0;

        //     coeffs.a1[i] = q * alph_h - 1.0;
        //     coeffs.a2[i] = 0.0;
        //     coeffs.b0[i] = 1.0;
        //     coeffs.b1[i] = -1.0;
        //     coeffs.b2[i] = 0.0;
        // }
        if (fabs(coeffs.a0[i]) < EPSILON_12E) {
            coeffs.a0[i] = EPSILON_10E;
        }
    }
    return coeffs;
}



}
